class GaoDe {
  constructor() {
    this.key = '4a21c5286a70d038988d4143d583913c';
    this.baseUrl = 'https://restapi.amap.com/v3';
  } 

  // 获取当前位置
  getLocation() {
    return new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'gcj02',
        geocode: true,
        success: (res) => {
          resolve({
            latitude: res.latitude,
            longitude: res.longitude,
            address: res.address || '未知位置'
          });
        },
        fail: (err) => {
          console.error('定位失败:', err);
          reject(err);
        }
      });
    });
  }

  // 地址搜索（POI搜索）
  searchPlace(keyword, location) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${this.baseUrl}/place/around`,
        data: {
          key: this.key,
          keywords: keyword,
          location: `${location.longitude},${location.latitude}`,
          city: location.name,
          radius: 100000,
          extensions: 'all',
          output: 'JSON'
        },
        success: (res) => {
          if (res.data.status === '1' && res.data.pois) {
            const results = res.data.pois.map(item => ({
              name: item.name,
              address: item.address,
              location: {
                latitude: parseFloat(item.location.split(',')[1]),
                longitude: parseFloat(item.location.split(',')[0])
              },
              distance: item.distance
            }));
            resolve(results);
          } else {
            reject(new Error(res.data.info || '搜索失败'));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }

   // 获取导航路线
   async getRoute(origin, destination, checkScenicSpots = false) {
     return new Promise((resolve, reject) => {
       uni.request({
         url: `${this.baseUrl}/direction/driving`,
         data: {
           key: this.key,
           origin: `${origin.longitude},${origin.latitude}`,
           destination: `${destination.longitude},${destination.latitude}`,
           extensions: 'all',
           strategy: 11, // 使用策略11获取多条路线
           output: 'JSON'
         },
         success: async (res) => {
           if (res.data.status === '1' && res.data.route?.paths?.length > 0) {
             // 基础路线处理
             const routes = res.data.route.paths.slice(0, 2).map((path, index) => ({
               id: index + 1,
               distance: path.distance + '米',
               duration: this._formatDuration(path.duration),
               points: this._parseRoutePoints(path.steps),
               steps: path.steps
             }));
			let spots = null;
             // 获取风景路线
             if (checkScenicSpots) {
               try {
                 const scenicRoute = await this._generateScenicRoute(
                   origin, 
                   destination, 
                   routes[0].points
                 );
                 if (scenicRoute) {
                   routes.push(...scenicRoute.path);
				   spots = scenicRoute.scenicSpots;
                 }
               } catch (e) {
                 console.error('生成风景路线失败:', e);
               }
             }
   
             resolve({routes,spots});
           } else {
             reject(new Error(res.data.info || '路径规划失败'));
           }
         },
         fail: reject
       });
     });
   }
   //获取路径周边的风景点
   async _getScenicSpotsAlongPath(points,type,radius = 1000) {
   	console.log(type)
     try {
       const scenicSpots = [];
       // 对每个路径点进行周边查询
       for (const point of this._simplifyPoints(points, 5)) {
         const res = await new Promise((resolve, reject) => {
           uni.request({
             url: `${this.baseUrl}/place/around`,
             data: {
               key: this.key,
               location: `${point.longitude},${point.latitude}`,
               types: type,
               radius: radius,
               radius: radius,
               extensions: 'base',
               offset: 5
             },
             success: resolve,
             fail: reject
           });
         });
   
         if (res.data.status === '1' && res.data.pois) {
           res.data.pois.forEach(async poi => {
             const spot = {
               id: poi.id,
               name: poi.name,
               location: {
                 latitude: parseFloat(poi.location.split(',')[1]),
                 longitude: parseFloat(poi.location.split(',')[0])
               },
               distance: poi.distance,
               originalPoint: point // 记录关联的原始路径点
             };
             // 去重
             if (!scenicSpots.some(s => s.id === spot.id)) {
   				const distance = await this.getDistance(point,spot.location)
   				if(Number(distance) <= 2000){
   					scenicSpots.push(spot);
   				}
             }
           });
         }
         // 每个点查询间隔100ms避免频繁请求
         await new Promise(resolve => setTimeout(resolve, 100));
       }
       return scenicSpots;
     } catch (e) {
       console.error('获取风景点失败:', e);
       return [];
     }
   }
   _getWaterPOITypes() {
     return [
       '110200', // 河流
       '110201', // 运河/水道
       '110202', // 湖泊
       '110203', // 水库
       '110204', // 海岸线
       '110205', // 岛屿
       '110206',  // 海滩
	   '110208'
     ].join('|');
   }
   // 生成风景路线
   async _generateScenicRoute(origin, destination, basePoints) {
     // 1. 获取有效风景点（导航距离<3km)
	 // 公园路线
     const scenicSpots = (await this._getScenicSpotsAlongPath(basePoints,'110101|110100'))
       .filter(spot => spot.distance < 2000)
       .slice(0, 3); // 最多选3个点
	
     if (scenicSpots.length === 0) return null;
   
     // 2. 计算所有关键路径段
     const routeSegments = [];
     let lastPoint = origin;
   
     // 按顺序处理每个风景点
     for (const spot of scenicSpots) {
       const toSpot = await this._getRoutePoints(lastPoint, spot.location);
	   routeSegments.push(...toSpot.points);
	   lastPoint = spot.location;
     }
   
     // 3. 添加最后一段到终点的路线
     const finalSegment = await this._getRoutePoints(lastPoint, destination);
     routeSegments.push(...finalSegment.points);
	 
	 // 景点路线
	 const scenicSpots2 = (await this._getScenicSpotsAlongPath(basePoints,'110000|110201|110202|11203|11204|11209'))
       .filter(spot => spot.distance < 2000)
       .slice(0, 3);
	 const routeSegments2 = [];
	 lastPoint = origin;
	 for (const spot of scenicSpots2) {
	   const toSpot = await this._getRoutePoints(lastPoint, spot.location);
	   routeSegments2.push(...toSpot.points);
	   lastPoint = spot.location;
	 }
	 const finalSegment2 = await this._getRoutePoints(lastPoint, destination);
	 routeSegments2.push(...finalSegment2.points);
	 
	 const scenicSpots3 = await this.searchPlace('湘江风光带',origin)
	 const routeSegments3 = [];
	 
	 const toSpot = await this._getRoutePoints(origin, scenicSpots3[0].location);
	 routeSegments3.push(...toSpot.points);
	 lastPoint = scenicSpots3[0].location;
	 
	 const finalSegment3 = await this._getRoutePoints(lastPoint, destination);
	 routeSegments3.push(...finalSegment3.points);
	 
	 
     // 4. 合并为完整路线
     return {
		path:[{
		   id: 3,
		   distance: Math.round(this._calculatePathDistance(routeSegments)) + '米',
		   duration: this._estimateDuration(routeSegments),
		   points: routeSegments,
		   isScenic: true,
		   scenicSpots: scenicSpots
	    },{
			id: 4,
			distance: Math.round(this._calculatePathDistance(routeSegments2)) + '米',
			duration: this._estimateDuration(routeSegments2),
			points: routeSegments2,
			isScenic: true,
			scenicSpots: scenicSpots2
		},{
			id: 5,
			distance: Math.round(this._calculatePathDistance(routeSegments3)) + '米',
			duration: this._estimateDuration(routeSegments3),
			points: routeSegments3,
			isScenic: true,
			scenicSpots: scenicSpots3
		}],
		scenicSpots:{
			'id1': scenicSpots,
			'id2': scenicSpots2,
			'id3': [scenicSpots3[0]]
		}
	 }
   }
   // 辅助方法：获取两点间的路线点
   async _getRoutePoints(start, end) {
     const res = await new Promise(resolve => {
       uni.request({
         url: `${this.baseUrl}/direction/driving`,
         data: {
           key: this.key,
           origin: `${start.longitude},${start.latitude}`,
           destination: `${end.longitude},${end.latitude}`,
           strategy: 2,
           extensions: 'base'
         },
         success: resolve,
         fail: () => resolve(null)
       });
     });
   
     if (res?.data?.status === '1') {
       return {
         points: this._parseRoutePoints(res.data.route.paths[0].steps),
         distance: res.data.route.paths[0].distance
       };
     }
     return { points: [], distance: 0 };
   }
   
   // 辅助方法：在路径中找到最近的点
   _findNearestPoint(point, pathPoints) {
     let minDist = Infinity;
     let nearestPoint = pathPoints[0];
     
     pathPoints.forEach(pathPoint => {
       const dist = this._calculateDistance(point, pathPoint);
       if (dist < minDist) {
         minDist = dist;
         nearestPoint = pathPoint;
       }
     });
     
     return nearestPoint;
   }
   
   // 辅助方法：计算两点间直线距离
   _calculateDistance(p1, p2) {
     const R = 6371000; // 地球半径
     const dLat = (p2.latitude - p1.latitude) * Math.PI / 180;
     const dLng = (p2.longitude - p1.longitude) * Math.PI / 180;
     const a = 
       Math.sin(dLat/2) * Math.sin(dLat/2) +
       Math.cos(p1.latitude * Math.PI / 180) * 
       Math.cos(p2.latitude * Math.PI / 180) *
       Math.sin(dLng/2) * Math.sin(dLng/2);
     return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
   }
   
   // 辅助方法：计算路径总长度
   _calculatePathDistance(points) {
     let distance = 0;
     for (let i = 1; i < points.length; i++) {
       distance += this._calculateDistance(points[i-1], points[i]);
     }
     return distance;
   }
   
   // 辅助方法：估算行程时间（米 -> 分钟）
   _estimateDuration(points) {
     const distance = this._calculatePathDistance(points);
     const minutes = Math.round(distance / 200); // 假设200米/分钟
     return minutes > 60 ? 
       `${Math.floor(minutes/60)}小时${minutes%60}分钟` : 
       `${minutes}分钟`;
   }
   
 // 获得从起点到目的地的到导航距离
 async getDistance(origin,destination){
	 const res = await new Promise(resolve => {
		 uni.request({
		 	url:`${this.baseUrl}/distance`,
			data:{
				key:this.key,
				origins:`${origin.longitude},${origin.latitude}`,
				destination:`${destination.longitude},${destination.latitude}`,
				type:1
			},
			success:resolve
		 })
	 })
	 if(res.data.status === '1'){
		return res.data.results[0].distance
	 }
 }
 // 辅助方法：简化路径点（减少API请求量）
   _simplifyPoints(points, maxPoints) {
	 if (points.length <= maxPoints) return points;
	 const step = Math.floor(points.length / maxPoints);
	 return points.filter((_, index) => index % step === 0);
   }
	_parseRoutePoints(steps) {
	   let points = [];
	   steps.forEach(step => {
		 points = points.concat(this._parsePolyline(step.polyline));
	   });
	   return points.map(p => ({ latitude: p.lat, longitude: p.lng }));
	 }
  // 解析高德返回的polyline字符串
  _parsePolyline(polyline) {
    if (!polyline) return [];
    const points = polyline.split(';').map(item => {
      const [lng, lat] = item.split(',');
      return {
        lat: parseFloat(lat),
        lng: parseFloat(lng)
      };
    });
    return points;
  }
  // 计算路径中心点
  _calculateCenter(points) {
    if (!points || points.length === 0) return null;
    
    let minLat = points[0].latitude;
    let maxLat = points[0].latitude;
    let minLng = points[0].longitude;
    let maxLng = points[0].longitude;
    
    points.forEach(point => {
      minLat = Math.min(minLat, point.latitude);
      maxLat = Math.max(maxLat, point.latitude);
      minLng = Math.min(minLng, point.longitude);
      maxLng = Math.max(maxLng, point.longitude);
    });
    
    return {
      latitude: (minLat + maxLat) / 2,
      longitude: (minLng + maxLng) / 2
    };
  }

  // 私有方法：格式化持续时间（保持不变）
  _formatDuration(seconds) {
    const mins = Math.floor(seconds / 60);
    if (mins < 60) {
      return `${mins}分钟`;
    }
    const hours = Math.floor(mins / 60);
    const remainingMins = mins % 60;
    return `${hours}小时${remainingMins}分钟`;
  }
}

export default GaoDe;